﻿using System.Collections.Generic;
using System.Linq;
using DynamicChart.Service.FunctionConversion;
using DynamicChart.Util;

namespace DynamicChart.Service.Step.GenerateSQL;

public class GenerateConnectionStep : GenerateAbstractSQLStep
{
    public GenerateConnectionStep(ISqlFunctionAdapter adapter) : base(adapter)
    {
    }
    
    public override void Process(IDictionary<string, object> data, IDictionary<string, string> res)
    {
        var connectionClauses = DataProcessor.EnumerateFields(data)
            .Where(t => t.Entity.ContainsKey("Connection"))
            .Select(t =>
            {
                return $@"{t.TableKey}.{t.ColumnKey} = {t.Entity["Connection"]}";
            })
            .Where(clause => !string.IsNullOrEmpty(clause))
            .ToList();

        if (connectionClauses.Count <= 0)
        {
            return;
        }
        
        res["where"] = (res["where"] == "" ? res["where"] : (res["where"] + " AND ")) + 
                       string.Join(" AND ", connectionClauses);
    }
}